package com.echoesnet.echoesshortvideo.views.dialog;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.Api.RequestHeader;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.DownLoadUtil;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.View.NumberProgressBar;
import com.google.gson.Gson;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.cause.ResumeFailedCause;
import com.liulishuo.okdownload.core.listener.DownloadListener1;
import com.liulishuo.okdownload.core.listener.assist.Listener1Assist;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.HashMap;

import me.iwf.photopicker.utils.FileUtils;

/**
 * @author yqh
 * @version 1.0
 * @createDate 2016/8/12
 * @Description 版本更新下载弹窗
 */
public class DownloadAlertDialog
{
    private static final String TAG = DownloadAlertDialog.class.getSimpleName();
    private Context mContext;
    private Dialog dialog;
    private TextView name;
    private ImageView image;
    NumberProgressBar pBar;
    private String url = "";

    public DownloadAlertDialog(Context context)
    {
        this.mContext = context;
    }

    public DownloadAlertDialog build()
    {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.download_notification_layout, null);
        image = (ImageView) view.findViewById(R.id.image);
        name = (TextView) view.findViewById(R.id.name);
        pBar = (NumberProgressBar) view.findViewById(R.id.progressbar);
        dialog = new Dialog(mContext, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        dialog.setCancelable(false);
        return this;
    }

    /**
     * 设置下载链接
     *
     * @param fileUrl 文件url
     * @return
     */
    public DownloadAlertDialog setDownLoadFileUrl(String fileUrl)
    {
        url = fileUrl;
        return this;
    }

    public DownloadAlertDialog setTitle(String title)
    {
        if (TextUtils.isEmpty(title))
        {
            title = "小录段子.apk";
        }
        name.setText(title);
        return this;
    }

    /**
     * 设置下载时图片
     *
     * @param imagePath
     * @return
     */
    public DownloadAlertDialog setImage(int imagePath)
    {
        image.setImageResource(imagePath);
        return this;
    }

//    private void downLoadAPK()
//    {
//        String fileKey = url.substring(url.lastIndexOf("/") + 1, url.length());
//        File sdcardPath = new File(CommonUtils.getRootDirPath(mContext));
//        if (!sdcardPath.exists())
//        {
//            sdcardPath.mkdir();
//        }
//
//        File downFile = new File(sdcardPath + fileKey);
//
//        CdnHelper.getInstance().downloadFile(fileKey, downFile, new Callback()
//        {
//            @Override
//            public void onSuccess(JSONObject message)
//            {
//                  Logger.t(TAG).d("路径" + CommonUtils.getRootDirPath(mContext));
//                if (dialog != null && dialog.isShowing())
//                    dialog.dismiss();
//                installAPK(downFile);
//            }
//
//            @Override
//            public void onProcess(long len, int contentLength)
//            {
//                int value = (int) (len *100/ contentLength);
//                Logger.t(TAG).d("下载进度:" + value+",len:"+len+",contentLength:"+contentLength);
//                pBar.setProgress(value);
//            }
//
//            @Override
//            public void onFail(JSONObject message)
//            {
//                ToastUtils.showShort("下载失败，请重试！");
//                if (dialog != null && dialog.isShowing())
//                {
//                    dialog.dismiss();
//                }
//            }
//        });
//    }

    private void downLoadApk()
    {
        File sdcardPath = new File(CommonUtils.getRootDirPath(mContext));
        if (!sdcardPath.exists())
        {
            sdcardPath.mkdir();
        }
        DownLoadUtil.getInstance().downloadFile(url, CommonUtils.getRootDirPath(mContext), "EchoesShortVideo.apk", new DownloadListener1()
        {
            @Override
            public void taskStart(@NonNull DownloadTask task, @NonNull Listener1Assist.Listener1Model model)
            {
                Logger.t(TAG).d("taskStart:"+model.getId()+" "+model.getTotalLength());
            }

            @Override
            public void retry(@NonNull DownloadTask task, @NonNull ResumeFailedCause cause)
            {
                Logger.t(TAG).d("retry:"+cause.name()+" ");
            }

            @Override
            public void connected(@NonNull DownloadTask task, int blockCount, long currentOffset, long totalLength)
            {
                Logger.t(TAG).d("connected:"+blockCount+" "+currentOffset+" "+totalLength);
            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, long totalLength)
            {
                Logger.t(TAG).d("progress:"+currentOffset+" "+totalLength);
                int value = (int) (currentOffset * 100/ totalLength);
                pBar.setProgress(value);
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull Listener1Assist.Listener1Model model)
            {
                Logger.t(TAG).d("taskEnd:"+model.getId()+" "+model.getTotalLength()+" EndCause "+cause.name()+" Exception "+(realCause==null?"null": realCause.getMessage()));
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
                if ("COMPLETED".equals(cause.name()))
                      installAPK(task.getFile());
            }
        });
    }

    private void installAPK(File file)
    {
        Logger.t(TAG).d( "在安装时候将token存入文件夹中");
        //在安装时候将token存入文件夹中，防止丢失后重新登录
        HashMap<String, String> paraMap = new HashMap<>();
        paraMap.put(RequestHeader.TOKEN, SharePreUtils.getToken());
        paraMap.put(RequestHeader.USER_ID, SharePreUtils.getUId());
        FileUtils.writeFile(CommonUtils.getRootDirPath(mContext) + "data/" + "appInnerFile.json", new Gson().toJson(paraMap), false);
        //会重新卸载安装
/*        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mContext.startActivity(intent);*/
        String authority = "com.echoesnet.echoesshortvideo.provider";
        mContext.startActivity(CommonUtils.getInstallAppIntent(file, authority, true));
//        Intent promptInstall = new Intent(Intent.ACTION_VIEW)
//                .setDataAndType(Uri.fromFile(file),
//                        "application/vnd.android.package-archive");
//        promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        mContext.startActivity(promptInstall);
        /*// 替换安装包
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
//        intent.setData(Uri.fromFile(file));
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
        intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
        intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
                mContext.getApplicationInfo().packageName);
        if (intent.resolveActivity(mContext.getPackageManager()) != null)
            mContext.startActivity(intent);*/
    }

    public void show()
    {
        dialog.show();
        //downLoadAPK();
        downLoadApk();
    }

}
